package com.example.foodisimportant.Network;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Callable;

public class LoginNetworkThread implements Callable<String> {
    private final String id,password,url;
    public LoginNetworkThread(String id, String password, String url){
        this.id=id;
        this.password = password;
        this.url = url;
    }
    @Override
    public String call() throws Exception {
        String data1;
        try {
            //开启连接
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            //拼接数据
            data1 = "userId="+ URLEncoder.encode(id, StandardCharsets.UTF_8.toString())+"&userPwd="+URLEncoder.encode(password,StandardCharsets.UTF_8.toString());
            //设置请求方法
            connection.setRequestMethod("POST");
            //允许输入输出
            connection.setDoInput(true);
            connection.setDoOutput(true);
            //写数据（也就是发送数据）
            connection.getOutputStream().write(data1.getBytes(StandardCharsets.UTF_8));
            byte [] bytes = new byte[1024];
            //获取返回的数据
            int len = connection.getInputStream().read(bytes);
            return new String(bytes,0,len,StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}
